from django.db import models
from django.contrib.auth.hashers import make_password, check_password
import uuid
from datetime import date

# 统一的员工模型（包含管理员、普通员工、安全员）
class Employee(models.Model):
    """
    统一的员工模型，使用角色标识区分不同类型的用户
    """
    GENDER_CHOICES = [
        ('男', '男'),
        ('女', '女'),
    ]
    
    EVALUATION_CHOICES = [
        ('优', '优'),
        ('良', '良'),
        ('中', '中'),
        ('差', '差'),
        ('待评价', '待评价'),
    ]
    
    STATUS_CHOICES = [
        ('启用', '启用'),
        ('停用', '停用'),
    ]

    # 基础字段（所有角色通用）
    id = models.UUIDField('用户ID', primary_key=True, default=uuid.uuid4, editable=False)
    username = models.CharField('用户名', max_length=150, unique=True, help_text='用于登录的用户名')
    password = models.CharField('密码', max_length=128, help_text='加密存储的密码')
    name = models.CharField('姓名', max_length=50)
    gender = models.CharField('性别', max_length=2, choices=GENDER_CHOICES, blank=True)
    phone = models.CharField('手机号', max_length=20, blank=True)
    email = models.EmailField('邮箱', blank=True)
    department = models.CharField('所属部门', max_length=50, blank=True)
    position = models.CharField('岗位', max_length=50, blank=True)
    hire_date = models.DateField('入职日期', null=True, blank=True)
    status = models.CharField('账号状态', max_length=10, choices=STATUS_CHOICES, default='启用')
    avatar = models.CharField('头像路径', max_length=200, blank=True, help_text='头像文件相对路径')
    bio = models.TextField('个人简介', blank=True, help_text='个人简介或备注信息')
    remarks = models.TextField('备注', blank=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('修改时间', auto_now=True)
    
    # 角色标识字段
    is_admin = models.BooleanField('是否管理员', default=False)
    is_safety_officer = models.BooleanField('是否安全员', default=False)
    is_employee = models.BooleanField('是否普通员工', default=True)
    
    # 管理员特有字段
    permissions = models.JSONField('权限列表', default=dict, blank=True)
    last_login_time = models.DateTimeField('最后登录时间', null=True, blank=True)
    
    # 普通员工特有字段
    employee_number = models.CharField('员工编号', max_length=20, blank=True, help_text='普通员工编号')
    contact = models.CharField('联系方式', max_length=20, blank=True)
    years_of_service = models.IntegerField('从业年限', default=0)
    total_tasks = models.IntegerField('整改任务数', default=0)
    completed_tasks = models.IntegerField('已完成整改数', default=0)
    completion_rate = models.FloatField('整改完成率', default=0.0)
    avg_completion_time = models.FloatField('平均整改时长(天)', default=0.0)
    last_remediation_date = models.DateField('最近整改日期', null=True, blank=True)
    evaluation = models.CharField('考核结果', max_length=10, choices=EVALUATION_CHOICES, default='待评价', blank=True)
    
    # 安全员特有字段
    safety_number = models.CharField('安全员编号', max_length=20, blank=True, help_text='安全员编号')
    license_number = models.CharField('安全资格证号', max_length=30, blank=True)
    management_scope = models.CharField('管理范围', max_length=100, blank=True)
    inspection_tasks = models.IntegerField('排查任务数', default=0)
    last_inspection_date = models.DateField('最近排查日期', null=True, blank=True)

    class Meta:
        verbose_name = '员工'
        verbose_name_plural = '员工'
        db_table = 'employees'
        indexes = [
            models.Index(fields=['username']),
            models.Index(fields=['is_admin', 'is_safety_officer', 'is_employee']),
        ]

    def set_password(self, raw_password):
        """设置加密密码"""
        self.password = make_password(raw_password)

    def check_password(self, raw_password):
        """验证密码"""
        return check_password(raw_password, self.password)

    def get_role_display(self):
        """获取角色显示名称"""
        if self.is_admin:
            return '管理员'
        elif self.is_safety_officer:
            return '安全员'
        elif self.is_employee:
            return '普通员工'
        return '未知角色'

    def save(self, *args, **kwargs):
        # 自动生成员工编号
        if self.is_employee and not self.is_admin and not self.is_safety_officer:
            if not self.employee_number:
                from datetime import datetime
                count = Employee.objects.filter(is_employee=True, is_admin=False, is_safety_officer=False).count()
                self.employee_number = f"EMP{datetime.now().strftime('%Y%m%d')}-{count + 1:03d}"
        
        # 自动生成安全员编号
        if self.is_safety_officer and not self.safety_number:
            from datetime import datetime
            count = Employee.objects.filter(is_safety_officer=True).count()
            self.safety_number = f"SAF{datetime.now().strftime('%Y%m%d')}-{count + 1:03d}"
        
        # 计算从业年限
        if self.hire_date:
            today = date.today()
            self.years_of_service = (today - self.hire_date).days // 365
        
        # 计算完成率（普通员工）
        if self.is_employee and self.total_tasks > 0:
            self.completion_rate = (self.completed_tasks / self.total_tasks) * 100
        else:
            self.completion_rate = 0.0
            
        super().save(*args, **kwargs)

    def __str__(self):
        role = self.get_role_display()
        if self.is_admin:
            return f"{self.username} - {self.name} ({role})"
        elif self.is_safety_officer:
            return f"{self.safety_number} - {self.name} ({role})"
        elif self.is_employee:
            return f"{self.employee_number} - {self.name} ({role})"
        return f"{self.name} ({role})"
